/*
 * Drunk Js
 * Author    :   Drunk
 * Website   :   http://drunkce.com,  http://idrunk.net
 * Date      :   16-05-26
 */

var wy = {
    staff : {
        /**
         * 员工选择器
         * @param c         配置{
         *  category: 类别{staff:员工, house:单元, structure:部门}(default:staff),
         *  estate: {pond:所在分公司数据, selected:选中分公司数据, other:当前物业所有分公司数据},
         *  title: 标题,
         *  single: 是否单选,
         *  staff_only: 是否仅取员工,
         *  staff_binded_only: 是否仅取绑定登录帐号的员工,
         *  staff_return: 是否返回员工
         *  call_yes: 选定回调
         * }
         * @param call_yes  选定回调
         * @returns {wy.staff.selecter.init}
         */
        selecter : function(c, call_yes){
            return new wy.staff.selecter.prototype.construct(c, call_yes);
        }
    },
    init : function(){
        wy.estate_selecter();
    },
    // 分公司选择
    estate_selecter : function(){
        if(!window.estate_selecter) return;
        var items = [];
        if(!window.estate_selecter_select_single) items.push('<label class="select-all" title="全选"><input type="checkbox" /><span>全选</span></label>');
        for(var i in estate_selecter)
            items.push('<label title="'+estate_selecter[i].name+'"><input type="checkbox" value="'+estate_selecter[i].id+'" '+(estate_selecter[i].checked ? 'checked' : '')+' /><span>' + estate_selecter[i].name + '</span></label>');

        $('.door .estate_selected').extenu({
            class_menu : 'estate_selecter',
            items : items,
            blurcall : wy.estate_select,
            align : 'right'
        }, 32);

        wy.estate_select_hack();
        wy.estate_selected_orignal = wy.estate_get_selected();
    },
    // hack选择操作, 必选一
    estate_select_hack : function(){
        var e_check_all = $('.estate_selecter label.select-all :checkbox'),
            e_check_item = $('.estate_selecter label:not(.select-all) :checkbox');
        e_check_all.bind('change', function(){ // 全选操作
            var e_this = $(this);
            if(e_this.is(':checked')){
                $('.estate_selecter label:not(.select-all) :checkbox').prop('checked', true)
            }else{
                $('.estate_selecter label:not(.select-all) :checkbox:gt(0)').prop('checked', false)
            }
        });
        e_check_item.bind('change', function(){
            var e_this = $(this);
            if(e_this.is(':checked')){
                if(window.estate_selecter_select_single) $('.estate_selecter :checkbox').not(e_this).prop('checked', false); // 是否单选模式
            }else{
                e_check_all.prop('checked', false);
                if(D.empty(wy.estate_get_selected())) return e_this.prop('checked', true); // 如果一个都木选中了, 则必须选中一个
            }
        });
        if(!window.estate_selecter_select_single && e_check_item.length === e_check_item.filter(':checked').length) e_check_all.prop('checked', true);
    },
    /**
     * 取选中分公司
     * @param takearr 是否取选中公司id数组
     * @returns {{}}
     */
    estate_get_selected : function(takearr){
        var rid_range = [];
        $('.estate_selecter label:not(.select-all) :checkbox:checked').each(function(i, e){
            rid_range.push(e.value);
        });
        return takearr ? rid_range : rid_range.sort().join(',');
    },
    // 选毕跳转
    estate_select : function(){
        var obj_selected = wy.estate_get_selected(),
            rid_range = wy.estate_get_selected(1);
        if(wy.estate_selected_orignal === obj_selected || D.empty(rid_range)) return false;
        $.ajax({
            url : '/base/estate_select.html?eids=' + rid_range.join(','),
            dataType : 'json',
            success : function(data){
                if($.isPlainObject(data) && data.status) location.reload();
            }
        });
    }
};

D.extend(wy.staff.selecter, {
    // 初始化
    init : function(data_structure, data_staff){
        if(!$.isArray(data_staff)) data_staff = [];
        wy_staffsel.c = {
            c_staff : {},
            c_staff_selected : {},
            data_structure : data_structure,        // 树形组织架构数据
            data_staff : data_staff,                // 员工列表数据
            e_structure : $e('.sst-main'),          // 树形组织架构
            e_staff : $e('.ssl-table'),             // 员工选择列表
            e_staff_selected : $e('.sss-table'),    // 员工选中列表
            e_select : $e('.ssc-select'),           // 选择
            e_unselect : $e('.ssc-unselect')        // 移除
        };
        wy_staffsel.structure_init();
        wy_staffsel.staff_init();
        wy_staffsel.staff_selected_init();
    },
    // 树形组件初始化
    structure_init : function(){
        wy_staffsel.c.e_structure.tree({
            data : wy_staffsel.c.data_structure,
            onSelect : wy_staffsel.structure_select,
            onLoadSuccess : function(){
                wy_staffsel.c.e_structure.tree('collapseAll');
                if(wy_staffsel.c.data_structure.length == 1)
                    wy_staffsel.c.e_structure.tree('expand', wy_staffsel.c.e_structure.tree('getRoot').target);
            }
        });
    },
    // 树形组件选中操作
    structure_select : function(node){
        wy_staffsel.staff_load(node, function(data){
            if(!$.isArray(data)) data = [];
            wy_staffsel.c.e_staff.datagrid('loadData', data);
        });
        wy_staffsel.c.e_structure.tree('toggle', node.target);
    },
    // 树形组件选中加载员工数据
    staff_load : function(node, callback){
        var i = 0,
            data = [],
            children = wy_staffsel.c.e_structure.tree('getChildren', node.target);
        if($.isArray(children) && !wy_staffsel.c.c_staff.staff_only) for(; i<children.length; i++){
            if(node != wy_staffsel.c.e_structure.tree('getParent', children[i].target)) continue;
            data[data.length] = children[i];
        }
        // 如果无级别标识或为最后一级, 则取其内容集
        if(!node.level || node.islastlevel) for(i=0; i<wy_staffsel.c.data_staff.length; i++){
            if(wy_staffsel.c.data_staff[i].sid == node.id) data[data.length] = wy_staffsel.c.data_staff[i];
        }
        callback.call(this, data);
    },
    // 员工列表初始化
    staff_init : function(){
        $.extend(wy_staffsel.c.c_staff, {'onSelect': wy_staffsel.staff_selected}); // 绑定行点击事件, 点击即选取
        wy_staffsel.c.e_staff.datagrid(wy_staffsel.c.c_staff);
        /*wy_staffsel.c.e_select.bind('click', wy_staffsel.staff_selected);
        wy_staffsel.c.e_unselect.bind('click', wy_staffsel.staff_unselected);*/
    },
    staff_selected : function(){
        var data_selections = wy_staffsel.c.e_staff.datagrid('getSelections');
        if($.isArray(data_selections)){
            if(wy_staffsel.c.c_staff.singleSelect) wy_staffsel.c.e_staff_selected.datagrid('loadData', []); // 若取单条, 则先清空呗
            for(var i=0; i<data_selections.length; i++){
                if(-1 == wy_staffsel.c.e_staff_selected.datagrid('getRowIndex', data_selections[i])) wy_staffsel.c.e_staff_selected.datagrid('appendRow', data_selections[i]);
            }
        }
    },
    // 已选员工列表初始化
    staff_selected_init : function(){
        $.extend(wy_staffsel.c.c_staff_selected, {'onSelect': wy_staffsel.staff_unselected}); // 绑定行点击事件, 点击即选取
        wy_staffsel.c.e_staff_selected.datagrid(wy_staffsel.c.c_staff_selected);
    },
    staff_unselected : function(index, row){
        wy_staffsel.c.e_staff_selected.datagrid('deleteRow', index);
    },
    // 取部门下员工
    staff_in_structure : function(node){
        var i = 0,
            data_return = [],
            data = wy_staffsel.c.e_structure.tree('getChildren', node.target);
        if(!$.isArray(data)) data = [];
        data.unshift(node);
        for(; i<data.length; i++){
            for(var j=0; j<wy_staffsel.c.data_staff.length; j++){
                if(wy_staffsel.c.data_staff[j].sid == data[i].id) data_return[data_return.length] = wy_staffsel.c.data_staff[j];
            }
        }
        return data_return;
    },
    // 取选中数据
    staff_selected_get : function(){
        return wy_staffsel.c.e_staff_selected.datagrid('getData');
    },
    receive : function(c){ // 把实例化的对象交给我吧
        $.extend(wy_staffsel.c.c_staff, c);
        wy_staffsel.c.e_staff.datagrid(wy_staffsel.c.c_staff);
        if(!D.empty(wy_staffsel.c.c_staff.selected)) for(var i=0; i<wy_staffsel.c.c_staff.selected.length; i++){ // 初始选中
            wy_staffsel.c.e_staff_selected.datagrid('appendRow', wy_staffsel.c.c_staff.selected[i]);
        }
    }
});

wy.staff.selecter.prototype = {
    construct : function(c, call_yes){
        var me = this;
        if(!$.isPlainObject(c)) c = {title : c};
        if($.isFunction(call_yes)) c.call_yes = call_yes;
        if(!c.category) c.category = 'staff';
        c.layer = top.layer;
        me.c = c; // 记录配置
        me.open();
    },
    // 打开弹窗
    open : function(){
        var me = this,
            url_map = {
                staff : '/base/staff_selecter.html?' + (me.c.staff_binded_only ? 'staff_binded_only=1' : ''),
                structure : '/base/structure_selecter.html?',
                house : '/base/house_selecter.html?'
            },
            url = url_map[me.c.category] || url_map.staff;
        url += '&estate_pond=' + me.c.estate;
        me.c.win_index = me.c.layer.open({
            type: 2,
            title: me.c.title,
            shadeClose: false,
            shade: [0.8, '#767676'],
            scrollbar: true,
            area: ['706px', '550px'],
            content: url,
            btn: ['确定', '取消'],
            yes: function(){ me.put_data.call(me); },
            success : function(e, i){
                me.c.sel_popup = $(e);
                me.c.sel_window = me.c.sel_popup.find('iframe')[0].contentWindow.window;
                var wy_staffsel_conf = {};
                if(me.c.single) wy_staffsel_conf.singleSelect = true;
                if(me.c.staff_only) wy_staffsel_conf.staff_only = true;
                if($.isFunction(me.c.call_selected)) wy_staffsel_conf.selected = me.c.call_selected.call(); // 默认选中
                me.c.sel_window.wy_staffsel.receive(wy_staffsel_conf); // 嗷~
            }
        });
    },
    // 推送数据
    put_data : function(){
        var me = this,
            selection = me.get_data(); // 取选中员工
        if($.isFunction(me.c.call_yes)) me.c.call_yes.call(me, selection); // 取数据回调
        me.close();
    },
    // 取选中数据
    get_data : function(){
        var me = this,
            i = 0,
            data = me.c.sel_window.wy_staffsel.staff_selected_get();
        data = (data && data.rows) ? data.rows : [];
        if(me.c.staff_return){ // 返回员工
            var data_new = [],
                data_new_part = [];
            for(; i<data.length; i++){
                if(!data[i].target){ // 直接员工数据
                    data_new[data_new.length] = data[i];
                }else{ // 根据部门取员工数据
                    data_new_part = me.c.sel_window.wy_staffsel.staff_in_structure(data[i]);
                    if($.isArray(data_new_part)) data_new = data_new.concat(data_new_part);
                }
            }
        }
        return data_new || data;
    },
    // 关闭弹窗
    close : function(){
    	this.c.layer.close(this.c.win_index);
    }
};
wy.staff.selecter.prototype.construct.prototype = wy.staff.selecter.prototype;
var wy_staffsel = wy.staff.selecter;

$(function(){ wy.init(); });